package com.bw.seckill_module.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.ref.WeakReference;

public class SecKillService extends Service {

    private long time = 0l;
    private TimeThread timeThread;

    public long getTime() {
        return time;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    //START_STICKY->配置当前服务为粘滞服务,当服务进程被kill 系统杀死时会自启动一次
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        time = intent.getLongExtra("time",0l);
        timeThread = new TimeThread(new TimeHandler(this));
        timeThread.start();
        return super.onStartCommand(intent,flags,startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new TimeBind();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timeThread.interrupt();
    }

    public class TimeBind extends Binder{
        public SecKillService getSecKillService(){
            return SecKillService.this;
        }
    }

    public static class TimeHandler extends Handler{

        private WeakReference<SecKillService>weakReference;

        public TimeHandler(SecKillService secKillService){
            weakReference = new WeakReference<>(secKillService);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (weakReference.get() == null)
                return;
            weakReference.get().time += 5;
        }
    }

    public static class TimeThread extends Thread{
        private TimeHandler handler;
        public TimeThread(TimeHandler handler){
            this.handler = handler;
        }
        @Override
        public void run() {
            super.run();
            while (!interrupted()){
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.sendEmptyMessage(0);
            }
        }
    }

}
